<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\model;

use think\Model;
use think\helper\Hash;
use think\Db;

/**
 * 工程模型
 */
class Order extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'mill_order';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    //工程状态
    public static $status = [
        -1 =>     '未通过',
        0 =>      '待审核',
        1 =>      '已审核',
    ];

    //外勤审核状态
    public static $waiback_status = [
        -1 =>     '未通过',
        0 =>      '待提交',
        1 =>      '待审核',
        2 =>      '已审核',
    ];

    //内勤审核状态
    public static $back_status = [
        -1 =>     '未通过',
        0 =>      '待提交',
        1 =>      '待审核',
        2 =>      '已审核',
    ];

    //面积表审核状态
    public static $archives_status = [
        -1 =>     '未通过',
        0 =>      '待提交',
        1 =>      '待审核',
        2 =>      '已审核',
    ];

    //优先级
    public static $urgent_status = [
        0 =>      '一般',
        1 =>      '加急',
        2 =>      '特急',
    ];

    //工艺喷涂
    public static $color_type = [
        1 =>      '一涂',
        2 =>      '二涂',
        3 =>      '三涂',
    ];

    //订单类型
    public static $types = [
        1       =>  '自有',
        2       =>  '外协',
        3       =>  '补下',
        4       =>  '样板',
    ];

    //自定义状态标签
    public static function status_tag($status=0,$label=''){
        switch ($status) {
            case '0': $class = 'warning';break;
            case '1': $class = 'info';break;
            case '2': $class = 'success';break;
            case '-1': $class = 'primary';break;
            case '-2': $class = 'primary';break;
            default: $class  = 'default';
        }
        $label = '<span class="label label-'.$class.'">'.$label.'</span>';

        return $label;
    }

    //获取所有订单信息
    public static function getList($field='engineering',$where = ''){
        $list = Db::name('mill_order')->where($where)->column($field,'id');
        return $list;
    }

    //获取指定工程所有的档案号/批次
    public static function getOrderP($order_pid=null,$where=[]){

        if(empty($where) && empty($order_pid))return '';
        if($order_pid)$where = ['o.order_pid'=>$order_pid];

        $archives_sn = Db::name('mill_order_archives_give')
            ->alias('g')
            ->leftJoin('mill_order o','g.order_id=o.id')
            ->where($where)
            ->order('g.order_id asc')
            ->column('distinct(o.archives_sn)');
        $count = count($archives_sn);
        $archives_sn = implode('/',$archives_sn);

        $batch = Db::name('mill_order_archives_give')
            ->alias('g')
            ->leftJoin('mill_order o','g.order_id=o.id')
            ->where($where)
            ->order('g.order_id asc')
            ->column('distinct(o.batch)');
        $batch = implode('/',$batch);

        $data = ['archives_sn'=>$archives_sn,'batch'=>$batch,'count'=>$count];

        return $data;
    }

    /**
     * 分析单元格合并
     * @param $v
     * @return array
     */
    public static function tableParseCell($v)
    {
        if (preg_match('/\[(.*)\]/', $v, $matches)) {
            $cell  = str_replace($matches[0], '', $v);
            $merge = explode(':', $matches[1]);
            $result = [
                'value'   => $cell,
                'colspan' => $merge[0],
                'rowspan' => isset($merge[1]) ? $merge[1] : '',
            ];
        } else {
            $result = [
                'value'   => $v,
                'rowspan' => '',
                'colspan' => '',
            ];
        }

        return $result;
    }

    //获取工程的金额
    public static function orderPrice($id = '',$field = 'order_id'){

        $data['address_price'] = Db::name('mill_order_archives_address_price')->where([$field=>$id])->sum('address_price');

        return $data;
    }

    //删除工程下的相关信息
    public static function orderDelete($field = 'order_id',$val = ''){
        $where = [];
        if($field == 'order_id'){
            $where[] = ['id','in',$val];
            $list = Db::name('mill_order')->where($where)->select();
            if(!empty($list)){
                foreach ($list as $v){

                    Db::name('mill_order')->where(['id'=>$v['id']])->delete();

                    //如果删除的是工程主体，则变更order_pid
                    if($v['id'] == $v['order_pid'])$order_pid = Db::name('mill_order')->where("order_pid = {$v['order_pid']} and id <> {$v['id']}")->order('id asc')->value('id');
                    if(!empty($order_pid)){
                        $update_where = ['order_pid'=>$v['order_pid']];
                        $update = ['order_pid'=>$v['order_pid']];
                        Db::name('mill_order')->where($update_where)->update($update);
                        Db::name('mill_order_archives')->where($update_where)->update($update);
                        Db::name('mill_order_archives_give')->where($update_where)->update($update);
                        Db::name('mill_order_archives_price')->where($update_where)->update($update);
                        Db::name('mill_order_archives_address')->where($update_where)->update($update);
                        Db::name('mill_order_archives_initial_price')->where($update_where)->update($update);
                    }
                }
            }
            $where = [['order_id','in',$val]];
            Db::name('mill_order_archives')->where($where)->delete();
            Db::name('mill_order_archives_give')->where($where)->delete();
            Db::name('mill_order_archives_initial_price')->where($where)->delete();
        }
        else if($field == 'order_pid'){
            $where[] = ['order_pid','in',$val];
            Db::name('mill_order')->where($where)->delete();
            Db::name('mill_order_archives')->where($where)->delete();
            Db::name('mill_order_archives_give')->where($where)->delete();
            Db::name('mill_order_archives_price')->where($where)->delete();
            Db::name('mill_order_archives_address')->where($where)->delete();
            Db::name('mill_order_archives_initial_price')->where($where)->delete();
        }
    }
    // 总工程 表格制作
    //print 0:编辑模式 1:打印模式
    /**
    'field'     =>  'ids',//字段名
    'title'     =>  '',//标题
    'type'      =>  'checkbox',//normal（常规列，无需设定） checkbox（复选框列） radio（单选框列） numbers（序号列） space（空列）
    'colspan'   =>  '1',//单元格所占列数
    'rowspan'   =>  '1',//单元格所占行数
    'width'     =>  '28px',//宽度
    'minWidth'  =>  '28px',//最小宽度
    'templet'   =>  '',//自定义列模板
    'fixed'     =>  true,//固定列。可选值有：left（固定在左）、right（固定在右）
    'escape'    =>  true,//当前列是否开启编码（转义 html）
    'totalRow'  =>  true,//是否开启该列的自动合计，详细查看：https://layui.dev/2.7/docs/modules/table.html#cols
     */
    public static function fromOrderPSelect($data = [],$print = 0){

        $layui_head = [
            [
                'field'     =>  'ids',
                //'type'      =>  'checkbox',
                'title'     =>  '<div class="layui-form check-all"><input type="checkbox" lay-skin="primary"></div>',
                'width'     =>  '30',
                'escape'    =>  false,
            ],
            [
                'field'     =>  'engineering',
                'title'     =>  '工程名称',
                'align'     =>  'center',
            ],
            [
                'field'     =>  'batch_sum',
                'title'     =>  '批次数量',
                'align'     =>  'center',
            ],
            [
                'field'     =>  'sales',
                'title'     =>  '内勤',
                'align'     =>  'center',
            ],
            [
                'field'     =>  'area_sum',
                'title'     =>  '产品面积',
                'align'     =>  'center',
            ],
        ];

        $table_head = $table_data = [];
        foreach ($layui_head as $lh){
            $table_head[] = $lh['title'];
        }
        $table_head = [$table_head];

        if(!empty($data['list'])){
            foreach ($data['list'] as $tdv){
                $tdv_data = [];

                foreach ($layui_head as $lh){

                    if($lh['field'] == 'ids')$tdv_data[] = '
<div class="layui-form check-one"><input type="checkbox" name="ids[]" value="'.$tdv['id'].'" lay-skin="primary"><div class="layui-form-checkbox" lay-skin="primary"><i class="layui-icon layui-icon-ok"></i></div></div>';
                    else $tdv_data[] = isset($tdv[$lh['field']])?$tdv[$lh['field']]:'';
                }

                $table_data[] = $tdv_data;
            }
        }

        return ['head'=>$table_head,'data'=>$table_data,'layui_head'=>$layui_head];
    }

    // 所有工程 表格制作
    //print 0:编辑模式 1:打印模式
    public static function fromOrderSelect($data = [],$print = 0){

        $layui_head = [
            [
                'field'     =>  'ids',
                //'type'      =>  'checkbox',
                'title'     =>  '<div class="layui-form check-all"><input type="checkbox" lay-skin="primary"></div>',
                'width'     =>  '28',
                'escape'    =>  false,
            ],
            [
                'field'     =>  'archives_sn',
                'title'     =>  '档案号',
                'align'     =>  'center',
            ],
            [
                'field'     =>  'engineering',
                'title'     =>  '工程名称',
                'align'     =>  'center',
            ],
            [
                'field'     =>  'number_sum',
                'title'     =>  '数量',
                'align'     =>  'center',
            ],
            [
                'field'     =>  'area_sum',
                'title'     =>  '面积(m²)',
                'align'     =>  'center',
            ],
            [
                'field'     =>  'do_id',
                'title'     =>  '移交后归属',
                'align'     =>  'center',
            ],
        ];

        $table_head = $table_data = [];
        foreach ($layui_head as $lh){
            $table_head[] = $lh['title'];
        }
        $table_head = [$table_head];

        if(!empty($data['list'])){
            foreach ($data['list'] as $tdv){
                $tdv_data = [];

                foreach ($layui_head as $lh){

                    if($lh['field'] == 'ids')$tdv_data[] = '
<div class="layui-form check-one"><input type="checkbox" name="ids[]" value="'.$tdv['id'].'" lay-skin="primary"><div class="layui-form-checkbox" lay-skin="primary"><i class="layui-icon layui-icon-ok"></i></div></div>';
                    else $tdv_data[] = isset($tdv[$lh['field']])?$tdv[$lh['field']]:'';
                }

                $table_data[] = $tdv_data;
            }
        }

        return ['head'=>$table_head,'data'=>$table_data,'layui_head'=>$layui_head];
    }

}
